<template>
  <CustomEcharts :id="props.id" height="220px" width="100%" :full-options="echartsOptions" :loading="false">
  </CustomEcharts>
</template>

<script setup>
// 引进Echarts 组件
import { onMounted, reactive, defineProps, watch } from "vue";
import CustomEcharts from './customEcharts.vue';
import * as echarts from 'echarts';

const props = defineProps({
  echartsData: Object,
  id: String
});

const echartsOptions = reactive({
  options: {}
});

const createOption = () => {
  if (!props.echartsData || !props.echartsData.series) return {};
  
  const colorArr = ['#5974C0', '#92CE78', '#FAC958', '#E88390', '#6FB9D1'];
  const series = props.echartsData.series.map((element, index) => ({
    name: element.name,
    type: "line",
    symbolSize: 5,
    showAllSymbol: false,
    smooth: true,  // 添加平滑曲线效果
    itemStyle: {
      color: colorArr[index]
    },
    lineStyle: {
      width: 2
    },
    data: element.data
  }));

  return {
    legend: {
      top: '1%',
      textStyle: {
        color: '#333'
      }
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: 'line'
      }
    },
    grid: {
      left: 0,
      right: '3%',
      bottom: '3%',
      top: '25%',
      containLabel: true
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: props.echartsData.xaxis || [],
      axisLabel: {
        interval: 'auto',
        textStyle: {
          fontSize: 12
        }
      },
      axisTick: {
        show: false
      },
      axisLine: {
        lineStyle: {
          color: "#D9D9D9"
        }
      }
    },
    yAxis: {
      type: "value",
      splitNumber: 5,
      min: 0,
      max: Math.max(...props.echartsData.series[0].data) , // 留出10%的空间
      axisLabel: {
        formatter: '{value}'
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        lineStyle: {
          type: "dashed",
          color: "#E5E7EB"
        }
      }
    },
    series: series
  };
};

// 监听数据变化，立即执行一次
watch(() => props.echartsData, (newVal) => {
  if (newVal) {
    echartsOptions.options = createOption();
  }
}, { 
  deep: true, 
  immediate: true  // 添加immediate确保首次加载时执行
});

onMounted(() => {
  echartsOptions.options = createOption();
});
</script>

<style scoped>
.chart-card {
  height: 300px;
  box-sizing: border-box;
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart-card > div {
  height: calc(100% - 40px); /* 减去标题的高度 */
}
</style>